// 主界面
;define(function(require, exports, module) {
    'use strict';
    var util = require("util");
    var base = require("base");
    var router = require("../hash/pageRouter");
    var css_this = require("./cargoRecord.css");
    var sure_deliveryAndsureSupervision = require("./sure_deliveryAndsureSupervision.js");
    var dialog = require("dialog");
    var validate = require("validate");
     var databind = require("databind");
    var pageIndex = 1,
        pageSize = 1000,
        totalPageCount = 1,
        totalRecordCount = 0; //分页初始化
    var imgSrc;
    var recieveNoticeId;
    var financeId; 
    var init = function(page){
    	recieveNoticeId = page.params.recieveNoticeId||base.getUrlParam("recieveNoticeId");
        financeId = page.params.financeId||base.getUrlParam("financeId");
        
        inquireTallyingPageList();
        sure_deliveryAndsureSupervision.init(page);
		initEvent();
		router.init();
		$("#leftMenu1").find(".leftMenu-item").removeClass("leftMenu-active");
		$("#leftMenu1 #undoneTaskList").parent(".leftMenu-item").addClass("leftMenu-active");
    };
	var initEvent = function(){
		//若未登录，则返回登陆页面
		if(base.getData("sid")==null||base.getData("sid")==""||base.getData("sid")==undefined){
			top.location.href="../login/login.html";
		}
		
		//点击理货 详情
			$(".content").on("click",".tallyingDetail",function(){
			var inventoryId = [];
           var $this = $(this).parents("tr.tr_style");
		   inventoryId.push($this.attr("inventoryId"));
			router.route("financing/tallyDetail.html?inventoryId="+inventoryId+"&recieveNoticeId="+recieveNoticeId+"&type=readOnly&financeId="+financeId,true);
	
		});
		
		//点击确认收货
		$(".content").on("click",".button_confirmTallying",function(){
				var tallyingId = [];
           var $this = $(this).parents("tr.tr_style");
		   tallyingId.push($this.attr("tallyingId"));
		   dialog.showConfirmDialog("确认收货","要确认此理货收货任务吗？",function(){
		   	base.fnAjax({
            action: "receiveConfirmTallying.json",
            oData: {
                tallyingId:tallyingId
            }, //传递参数
            fnSuccess: function(data) {
                if (data.status == 200) {
                	 base.alert(1,"理货收货确认成功");
             	router.route("financing/cargoRecord.html?recieveNoticeId="+recieveNoticeId+"&financeId="+financeId,true);
		    } else {
                    base.alert(2,data.message);
                }
            }
        });
		   });
		});
		
		//点击确认监管
		$(".content").on("click",".button_superviseTallying",function(){
				var tallyingId = [];
           var $this = $(this).parents("tr.tr_style");
		   tallyingId.push($this.attr("tallyingId"));
		   dialog.showConfirmDialog("确认监管","要确认此理货收货监管吗？",function(){
		   	base.fnAjax({
            action: "superviseTallying.json",
            oData: {
                tallyingId:tallyingId
            }, //传递参数
            fnSuccess: function(data) {
                if (data.status == 200) {
                	 base.alert(1,"理货收货监管确认成功");
             	router.route("financing/cargoRecord.html?recieveNoticeId="+recieveNoticeId+"&financeId="+financeId,true);
		    } else {
                    base.alert(2,data.message);
                }
            }
        });
		   });
		});
		$(".page-header").on("click","a",function(){
			var path = $(this).attr("id");
			router.route("newTaskList/"+path+".html?recieveNoticeId="+recieveNoticeId,true);
		});
		
		$(".page-content").on("click","#undoneTaskDetail",function(){
			var path = $(this).attr("id");
			router.route("newTaskList/"+path+".html?recieveNoticeId="+recieveNoticeId,true);
		});
		
		$(".page-content-main").on("click","#tallyListGenerate",function(){
			var path = $(this).attr("id");
			router.route("newTaskList/"+path+".html");
		});
		
		$(".page-content").on("click",".handle-detail",function(){
			var va = $(this).parents(".table-base-body-item").attr("id");
			$(this).parents(".table-base-body").find(".children_"+va).toggle();
		});
		
		//点击完成
		$(".content").on("click",".button_finish",function(){
				var tallyingId = [];
           var $this = $(this).parents("tr.tr_style");
		   tallyingId.push($this.attr("tallyingId"));
		   dialog.showDialog($("#finishedTask-dialog"),function(){});
		   $("#surefinished").on("click",function(){
		   	databind.fillForm($(".finishedTask"),{tallyingId:tallyingId});
		   	databind.submitDom($(".finishedTask"),function(){
		   		 base.alert(1,"完成理货任务");
                	  dialog.hideDialog($("#finishedTask-dialog"));
                	  router.route("newTaskList/undoneCargoRecord.html?recieveNoticeId="+recieveNoticeId,true);
            
		   	});
		   });
		});
		
		//button_unusualReport点击异常上报
			$(".content").on("click",".button_unusualReport",function(){
				var tallyingId = [];
           var $this = $(this).parents("tr.tr_style");
		   tallyingId.push($this.attr("tallyingId"));
		   databind.fillForm($(".unusualReportTask"),{tallyingId:tallyingId});
			dialog.showDialog($("#unusualReportTask-dialog"),function(){});
			$("#sureabnormal").on("click",function(){
				
				databind.submitDom($(".unusualReportTask"),function(){
					base.alert(1,"异常上报成功");
					databind.hideDialog($(".unusualReportTask"));
					router.route("newTaskList/undoneCargoRecord.html?recieveNoticeId="+recieveNoticeId,true);
               
				});
			});
		});
		
		//上传异常照片
		$("#unusualReportTask-dialog").on("change","#uploadFileAbnormalFile",function(){
			
			 uploadFileImg($(this).parent().parent(),"uploadFileAbnormalFile");
		});
		
		//上传异常录音
		$("#unusualReportTask-dialog").on("change","#uploadFileSoundRecorde",function(){
			
			 uploadFile($(this).parent().parent(),"uploadFileSoundRecorde");
		});
		//点击理货 非自理 
			$(".content").on("click",".tallyingA",function(){
			var inventoryId = [];
           var $this = $(this).parents("tr.tr_style");
		   inventoryId.push($this.attr("inventoryId"));
			router.route("newTaskList/tallyDetail.html?inventoryId="+inventoryId,true);
	
		});
		// 点击理货
		$(".content").on("click",".button_tally",function(){
			var tallyingId = [];
           var $this = $(this).parents("tr.tr_style");
		   tallyingId.push($this.attr("tallyingId"));
			router.route("newTaskList/tallyDetail.html?recieveNoticeId="+recieveNoticeId+"&tallyingId="+tallyingId,true);
	
		});
		//点击修改
		$(".content").on("click",".button_update",function(){
			var tallyingId = [];
           var $this = $(this).parents("tr.tr_style");
		   tallyingId.push($this.attr("tallyingId"));
			router.route("newTaskList/tallyListGenerate.html?recieveNoticeId="+recieveNoticeId+"&tallyingId="+tallyingId,true);
	
		});
		
		//点击确认
		$(".content").on("click",".button_confirm",function(){
			var tallyingId = [];
           var $this = $(this).parents("tr.tr_style");
		   tallyingId.push($this.attr("tallyingId"));
		   dialog.showDialog($("#confirmTask-dialog"),function(){});
		   $("#confirmTask-dialog").on("click",".dialogBtn",function(){
		   	databind.fillForm($("#confirmTask-dialog"),{tallyingId:tallyingId});
		   	 databind.submitDom($(".confirmTask"),function(){
		   	    dialog.hideDialog($("#confirmTask-dialog"));
               	router.route("newTaskList/undoneCargoRecord.html?recieveNoticeId="+recieveNoticeId,true);
              
		   	 });
		   });
		});
		//点击上报
		$(".content").on("click",".button_report",function(){
				var tallyingId = [];
           var $this = $(this).parents("tr.tr_style");
		   tallyingId.push($this.attr("tallyingId"));
		   dialog.showDialog($("#reportTask-dialog"),function(){});
		   $("#sureUpdFirst").on("click",function(){
		   	 reportTallying(tallyingId);
		   });
		});
		//点击删除图片和文件
		$("#unusualReportTask-dialog").on("click",".closeLayer",function(){
			var number = $(this).parent().parent().find(".finance-field-img").length;
			$(this).parent().remove();
			if(number==8){
                  	 $(".uploadFileAbnormalFile").css("display","block");
                  }
		});
		//点击删除图片和文件
		$("#unusualReportTask-dialog").on("click","#closeLayer1",function(){
			$(this).parent().remove();
			 $(".uploadFileSoundRecorde").css("display","block");
		});
    };
     var uploadFileImg = function(dom,id){//p标签的dom,img的id
    	 if ($("#"+id).val() != "") {
            var fileType = "jpg,png,bmp";
            var prompt  = validate.validateFileType(dom.find("#"+id),fileType);
            if(prompt.length > 1){
                base.alert(2,prompt);
                return;
            }
            $.ajaxFileUpload({
                url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
                secureuri: false,
                fileElementId: id,
                dataType: 'json',
                success: function(data) {
                	var imgSrc = "";
                	var html = "";
            		imgSrc = data.data[0].fileUuid;
            		html = "<label class=\"finance-file\"><img  src=\"/finance/api/1.0/downloadFile.file?fileUuid="+imgSrc+"\" class=\"finance-field-img\"  alt=\""+imgSrc+"\"  /> <a class=\"closeLayer\" ></a></label>";
                    dom.append(html);//
                    savefilesUuid(dom);
                    var number = dom.find(".finance-field-img").length;
	                if(number==8){
	                  	$(".uploadFileAbnormalFile").css("display","none");
	                }
                },
                complete: function(xml) {
                },
                error: function(data, status, e) {
                	if (data.msg == null) {
						base.alert(2, "文件太大无法上传");
					} else {
						base.alert(2, data.msg);
					}
                }
            });
        } else {
            base.alert(3, "请选择文件！");
        }
    }
     
     var uploadFile = function(dom,id){//p标签的dom,img的id
    	 if ($("#"+id).val() != "") {
            $.ajaxFileUpload({
                url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
                secureuri: false,
                fileElementId: id,
                dataType: 'json',
                success: function(data) {
                	var imgSrc = "";
                	var html = "";
                		 imgSrc = data.data[0].fileUuid;
                		 html = "<label class=\"finance-file\"><img  src=\"../../../res/png/voice_icon.png\" class=\"finance-field-img\"  alt=\""+imgSrc+"\"  /> <a id=\"closeLayer1\" class=\"closeLayer\" ></a></label>";
                   dom.append(html);//
                   $("#soundRecorde").val(imgSrc);
                   $(".uploadFileSoundRecorde").css("display","none");
                },
                complete: function(xml) {
                },
                error: function(data, status, e) {
                	if (data.msg == null) {
						base.alert(2, "文件太大无法上传");
					} else {
						base.alert(2, data.msg);
					}
                }
            });
        } else {
            base.alert(3, "请选择文件！");
        }
    }
     
      //更新fileUuuid保存字段
    var savefilesUuid = function(dom){
    		var filesUuids = "";
    	var imgDom =dom.find(".finance-field-img");
    	  var number = imgDom.length;
                 $.each(imgDom,function(i,object){
                 	if(i==number-1){
                 		filesUuids += object.alt;
                 	}else{
                 		filesUuids += object.alt+",";
                 	}
                 
                 });
              $("#abnormalFile").val(filesUuids);
            
    }
    
    //上报理货任务(物流公司)
    var reportTallying = function(tallyingId){
    	base.fnAjax({
            action: "reportTallying.json",
            oData: {
                tallyingId:tallyingId
            }, //传递参数
            fnSuccess: function(data) {
                if (data.status == 200) {
                	 base.alert(1,"上报成功");
                	  dialog.hideDialog($("#reportTask-dialog"));
                	  router.route("newTaskList/undoneCargoRecord.html?recieveNoticeId="+recieveNoticeId,true);
                } else {
                    base.alert(2,"信息获取失败");
                }
            }
        });
    }
    
    //查询理货任务列表
    var inquireTallyingPageList = function(){
    	base.fnAjax({
            action: "inquireTallyingPageList.json",
            oData: {
            	pageIndex: pageIndex,
                pageSize: pageSize,
                recieveNoticeId:recieveNoticeId
            }, //传递参数
            fnSuccess: function(data) {
                if (data.status == 200) {
                	var tpl = $("#cargoRecordTpl").html();
                    var html = juicer(tpl, data);
                    $(".cargoRecordContent").html(html);
                } else {
                    base.alert(2,"信息获取失败");
                }
            }
        });
    }
    return {
        init:init
    };
});